/*
 * ECARX Technology Limited is the owner of the copyright and the trade secret of this software.
 * Without permission, no one has the right to obtain, disclose or use this software in any way.
 */
package com.ecarx.systemui.plugin.controller;

import android.content.ContentResolver;
import android.content.Context;
import android.database.ContentObserver;
import android.net.Uri;
import android.os.Handler;
import android.provider.Settings;

import com.ecarx.systemui.plugin.utils.LogUtils;

import org.jetbrains.annotations.NotNull;

/**
 * @author : jiangjiao.ying
 * @date : 2022/08/17
 * @describe : MessageController
 */
public class MessageController {
    private String TAG = MessageController.class.getSimpleName();
    private Context mContext;
    private static MessageController mController;
    private IOnNotifyMessageIconChange mListener;

    private ContentResolver mContentResolver;
    public static final String NOTIFICATION_COUNT = "ecarx_notification_count";

    public MessageController(Context context) {
        mContext = context;
        initUpdate();
    }

    public static synchronized MessageController getInstance(Context context) {
        if (mController == null) {
            mController = new MessageController(context);
        }
        return mController;
    }




    private void initUpdate() {
        try {
            mContentResolver = mContext.getContentResolver();
            mContentResolver.registerContentObserver(Settings.Global.getUriFor(NOTIFICATION_COUNT), true, new ContentObserver(new Handler()) {
                @Override
                public void onChange(boolean selfChange, Uri uri) {
                    LogUtils.d(TAG, "onChange: uri : " + uri);
                    super.onChange(selfChange, uri);
                    if (mListener != null) {
                        mListener.onNotifyMessageIconChange();
                    }
                }
            });
        } catch (Exception e) {
            LogUtils.e(TAG, e.toString());
        }
    }

    public int getMessageCount() {
        int unReadCount = Settings.Global.getInt(mContext.getContentResolver(), NOTIFICATION_COUNT, 0);
        LogUtils.d(TAG, "getMessageCount unReadCount : " + unReadCount);
        return unReadCount;
    }


    public interface IOnNotifyMessageIconChange {
        void onNotifyMessageIconChange();
    }

    public void setOnNotifyMessageIconChangeListener(IOnNotifyMessageIconChange listener){
        mListener = listener;
    }

}
